
/***************************************************************
* 河南科技大学一队
*
* 函数名称：void GetHistGram(uint8_t Image[Height][Width])
* 功能说明：获取图像的灰度信息
* 参数说明：
* 函数返回：void
* 修改时间：2018年3月7日
* 备 注：下面是前面我弄的C#版本大津法二值化化转化为C语言的。
***************************************************************/ 

#include"binaryzation.h"

extern uint8 image[MT9V032_H][MT9V032_W];

uint8 HistGram[MT9V032_W*MT9V032_H];
/*0 黑色 255 白色*/
uint8 binary_image[MT9V032_H][MT9V032_W];
uint8 Threshold;


void GetHistGram(uint8 Image[MT9V032_H][MT9V032_W])
{
    int X,Y;
    for (Y = 0; Y < 256; Y++)
    {
        HistGram[Y] = 0; //初始化灰度直方图
    }
    for (Y = 0; Y < MT9V032_H; Y++)
    {
        for (X = 0; X < MT9V032_W; X++)
        {
            HistGram[Image[Y][X]]++; //统计每个灰度值的个数信息
        }
    }
} 

uint8 OSTUThreshold()
{
    int16 Y;
    uint32 Amount = 0;
    uint32 PixelBack = 0;
    uint32 PixelIntegralBack = 0;
    uint32 PixelIntegral = 0;
    int32_t PixelIntegralFore = 0;
    int32_t PixelFore = 0;
    double OmegaBack, OmegaFore, MicroBack, MicroFore, SigmaB, Sigma; // 类间方差;
    int16 MinValue, MaxValue;
    uint8 Threshold = 0;
    
    for (MinValue = 0; MinValue < 256 && HistGram[MinValue] == 0; MinValue++) ;        //获取最小灰度的值
    for (MaxValue = 255; MaxValue > MinValue && HistGram[MinValue] == 0; MaxValue--) ; //获取最大灰度的值
    
    if (MaxValue == MinValue) 
    {
        return MaxValue;          // 图像中只有一个颜色    
    }
    if (MinValue + 1 == MaxValue) 
    {
        return MinValue;      // 图像中只有二个颜色
    }
    
    for (Y = MinValue; Y <= MaxValue; Y++)
    {
        Amount += HistGram[Y];        //  像素总数
    }
    
    PixelIntegral = 0;
    for (Y = MinValue; Y <= MaxValue; Y++)
    {
        PixelIntegral += HistGram[Y] * Y;//灰度值总数
    }
    SigmaB = -1;
    for (Y = MinValue; Y < MaxValue; Y++)
    {
        PixelBack = PixelBack + HistGram[Y];    //前景像素点数
        PixelFore = Amount - PixelBack;         //背景像素点数
        OmegaBack = (double)PixelBack / Amount;//前景像素百分比
        OmegaFore = (double)PixelFore / Amount;//背景像素百分比
        PixelIntegralBack += HistGram[Y] * Y;  //前景灰度值
        PixelIntegralFore = PixelIntegral - PixelIntegralBack;//背景灰度值
        MicroBack = (double)PixelIntegralBack / PixelBack;//前景灰度百分比
        MicroFore = (double)PixelIntegralFore / PixelFore;//背景灰度百分比
        Sigma = OmegaBack * OmegaFore * (MicroBack - MicroFore) * (MicroBack - MicroFore);//g
        if (Sigma > SigmaB)//遍历最大的类间方差g
        {
            SigmaB = Sigma;
            Threshold = Y;
        }
    }
    return Threshold;
}
/*图像二值化处理*/
void binary_process()
{
    for(int i=0;i<MT9V032_W;i++)
    {
        for(int j=0;j<MT9V032_W;j++)
        {
            binary_image[i][j]=image[i][j]>=Threshold? TRACK_WHITE:TRACK_BLACK;
        }
    }
}

